package com.wentao.thisService.common;

import com.wentao.thisCommon.common.ConvertEntity;
import com.wentao.thisCommon.common.EnumsBase;
import com.wentao.thisCommon.model.BaseContent;
import com.wentao.thisCommon.model.BaseEntity;
import com.wentao.thisCommon.model.ResultBase;
import com.wentao.thisFacade.common.enums.SuccessCode;
import com.wentao.thisService.model.entities.BaseUpdateEntity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

//import com.wentao.thisCommon.common.ConvertEntity;
//import com.wentao.thisCommon.common.EnumsBase;
//import com.wentao.thisCommon.model.BaseContent;
//import com.wentao.thisCommon.model.BaseEntity;
//import com.wentao.thisCommon.model.BaseUpdateEntity;
//import com.wentao.thisCommon.model.ResultBase;

public class CommonFunction {

    protected static final Properties PROPERTIES = new Properties(System.getProperties());
    protected static final String DateBaseFormat = "yyyy/MM/dd";
    protected static final String DateTimeBaseFormat = "yyyy/MM/dd HH:mm:ss";
    protected static final String Version = "1.0.0";

//    public static String GetNowDateString(){
//        Date currentTime = new Date();
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String dateString = formatter.format(currentTime);
//        return dateString;
//    }

//    public static UserInfoEntity GetUsers(String token, String userName) {
//        String key = String.format("%s_%s", token, userName);
//        UserInfoEntity user = RedisExecutor.getMap(ConstString.Login, key, UserInfoEntity.class);
//        return user;
//    }

//    public static UserInfoEntity GetUsers(String token, String userName) {
//        UserLoginInfo userLoginInfo = RedisExecutor.getMap(ConstString.USER_LOGIN_INFO, userName, UserLoginInfo.class);
//        if (null != userLoginInfo) {
//            UserInfoEntity userInfoEntity = new UserInfoEntity();
//            if (null != token && token.equals(userLoginInfo.getToken())) {
//                userInfoEntity.setId(userLoginInfo.getUserId());
//                userInfoEntity.setToken(userLoginInfo.getToken());
//                userInfoEntity.setUserCode(userLoginInfo.getUserCode());
//                userInfoEntity.setStatus(userLoginInfo.getStatus());
//                userInfoEntity.setPermissionCodes(userLoginInfo.getPermissionCodes());
//            }
//            return userInfoEntity;
//        }
//        return null;
//    }

    public static String CreateUUIDString() {
        return CreateUUID().toString();
    }

    public static UUID CreateUUID() {
        return UUID.randomUUID();
    }

    public static String SysFileSeparator() {
        return PROPERTIES.getProperty("file.separator");
    }

    public static String SysEncoding() {
        return PROPERTIES.getProperty("file.encoding");
    }

    public static String replaceBlank(String str) {

        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    public static <T> ResultBase<T> ResultOk(T rtn) {
        return ResultMessage(rtn, SuccessCode.SYSTEM_SUCCESS);
    }

    public static <T> ResultBase<T> ResultMessage(T rtn, EnumsBase enumsVal) {
        ResultBase<T> result = new ResultBase<T>(rtn, enumsVal.getMessage(), enumsVal.getCode());
        return result;
    }

    public static Map<String, String> GetUrlParameter(HttpServletRequest request) {
        String queryStr = request.getQueryString();
        return GetUrlParameter(queryStr);
    }

    public static Map<String, String> GetUrlParameter(String str) {
        Map<String, String> map = new Hashtable<String, String>();
        if (null != str) {
            String[] p = str.split("&");
            for (int i = 0; i < p.length; i++) {
                String[] s = p[i].split("=");
                if (s.length > 1) {
                    map.put(s[0], s[1]);
                }
            }
        }

        return map;
    }

    public static String Null2Empty(String str) {
        return null == str ? "" : str;
    }

    public static String Empty2Null(String str) {
        return "".equalsIgnoreCase(str) ? null : str;
    }

    public static boolean IsNullOrEmpty(String str) {
        return null == str || str.length() == 0;
    }

    public static boolean IsNullOrEmptyByObject(Object str) {
        return null == str || str.toString().trim().length() == 0;
    }

    public static String CreateRandom(int len) {
        Random ran = new Random();
        String[] a = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
                "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
                "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
                "9"};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            double b = ran.nextDouble();
            int c = (int) (b * a.length);
            sb.append(a[c]);
        }
        return sb.toString();
    }

    public static String CreateRandomNumer(int len) {
        Random ran = new Random();
        String[] a = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            double b = ran.nextDouble();
            int c = (int) (b * a.length);
            sb.append(a[c]);
        }
        return sb.toString();
    }

    public static String GetNowDateString() {
        Date dt = new Date();
        return GetLocalDateString(dt);
    }

    public static String GetNowDateString(String format) {
        Date dt = new Date();
        return GetLocalDateString(dt, format);
    }

    public static String GetLocalDateString(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat(DateTimeBaseFormat);
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String GetLocalDateString(Date date, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String GetDateByTime(Long time) {
        Date dt = new Date(time);
        return GetLocalDateString(dt);
    }

    public static Date AddDateTime(Date date, Integer time) {
        Long time_val = date.getTime() + time;
        return new Date(time_val);
    }

    public static Date AddDateTime(Integer time) {
        return AddDateTime(new Date(), time);
    }

    public static String ConvertToDateByExcel(String date) {
        return ConvertToDateByExcel(date, DateBaseFormat);
    }

    public static String ConvertToDateByExcel(String date, String format) {

        if (null == date) {
            return null;
        }

        try {
            Integer month = Integer.parseInt(date);
            Calendar c = new GregorianCalendar(1900, 0, -1);
            c.add(5, month);
            return GetLocalDateString(c.getTime());
        } catch (Exception ex) {
        }

        try {
            SimpleDateFormat formatter = new SimpleDateFormat(format);
            Date dt = formatter.parse(date);
            return GetLocalDateString(dt);
        } catch (Exception ex) {
        }

        return null;
    }

    public static Date GetLocalDate(String date) throws ParseException {
        return GetLocalDate(date, DateBaseFormat);
    }

    public static Date GetLocalDate(String date, String format) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        Date dt = formatter.parse(date);
        return dt;
    }

    public static void ImageResize(String fileName, int w, int h) throws Exception {
        File file = new File(fileName);
        Image img = ImageIO.read(file);
        int width = img.getWidth(null);
        int height = img.getHeight(null);
        String ext = fileName.substring(fileName.lastIndexOf('.') + 1);
        String name = fileName.substring(0, fileName.lastIndexOf('.'));
        String filePath = String.format("%s%sX%s.%s", name, w, h, ext);

        if (width > height) {
            h = (int) (height * w / width);
        } else {
            w = (int) (width * h / height);
        }

        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        boolean ok = image.getGraphics().drawImage(img, 0, 0, w, h, null);
        if (ok) {
            File destFile = new File(filePath);
            ImageIO.write(image, ext, destFile);
        }
    }

    public static String ChangePath(String path, String separator) {
        String systemSeparator = SysFileSeparator();
        return path.replace(separator, systemSeparator);
    }

    public static String CreateDir(String dir) {
        String systemSeparator = SysFileSeparator();
        String[] sp = null;
        if (dir.indexOf("/") >= 0) {
            sp = dir.split("/");
        } else {
            sp = dir.split("\\\\");
        }

        String path = ConvertEntity.Empty;
        for (int i = 0; i < sp.length; i++) {
            if (i == 0 || sp[i].length() > 0) {
                path += sp[i];
                File pathStr = new File(path);
                if (!pathStr.isFile()) {
                    path += systemSeparator;
                    if (!pathStr.exists()) {
                        pathStr.mkdir();
                    }
                }
            }
        }

        return path;
    }

    public static String CreateDirAndJoin(String... dir) {
        String path = ConvertEntity.Empty;
        for (int i = 0; i < dir.length; i++) {
            path = CreateDir(path + dir[i]);
        }

        return path;
    }

    public static void Unzip(String path, String outpath) throws Exception {
        Unzip(path, outpath, SysEncoding());
    }

    public static <T> T SetNullValue(Object obj, Object value) {
        Object rtn = null == obj ? value : obj;
        return (T) rtn;
    }

    public static void Unzip(String path, String outpath, String charset) throws Exception {
        File file = new File(path);
        File outFile = null;
        ZipFile zipFile = new ZipFile(file, Charset.forName(charset));
        ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file), Charset.forName(charset));
        ZipEntry entry = null;
        InputStream input = null;
        OutputStream output = null;
        while ((entry = zipInput.getNextEntry()) != null) {
            outFile = new File(outpath + File.separator + entry.getName());
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdir();
            }

            if (!outFile.exists() && entry.isDirectory()) {
                outFile.mkdir();
            } else if (!outFile.exists()) {
                outFile.createNewFile();
                input = zipFile.getInputStream(entry);
                output = new FileOutputStream(outFile);
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    output.write(temp);
                }
                input.close();
                output.close();
            }
        }
    }

    public static String CreateMd5(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer(ConvertEntity.Empty);
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static String Encode(String str, String charset) throws UnsupportedEncodingException {
        return java.net.URLEncoder.encode(str, charset).replace("+", "%20");
    }

    public static String Encode(String str) throws UnsupportedEncodingException {
        return Encode(str, ConvertEntity.CHARSET);
    }

    public static String ConvertEncoding(String str, String coding) throws UnsupportedEncodingException {
        byte[] n = str.getBytes();
        return new String(n, coding);
    }

    public static boolean RegexString(String regex, String str) {
        return Pattern.matches(regex, str);
    }

    public static byte[] Encrypt(String content, String password) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128, new SecureRandom(password.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        byte[] byteContent = content.getBytes(ConvertEntity.CHARSET);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] result = cipher.doFinal(byteContent);
        return result;
    }

    public static byte[] DesEncrypt(byte[] content, String password) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128, new SecureRandom(password.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] result = cipher.doFinal(content);
        return result;
    }

    public static String Encrypt(String data, String key, String iv) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);

            return new sun.misc.BASE64Encoder().encode(encrypted);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String DesEncrypt(String data, String key, String iv) throws Exception {
        try {

            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void ExportCVS(String path, List<?> list) throws Exception {
        ExportCVS(path, list, new HashMap<String, String>());
    }

    public static void ExportCVS(String path, List<?> list, Map<String, String> head) throws Exception {
        ExportCVS(path, ConvertEntity.CovertToMap(list), head, ConvertEntity.CHARSET);
    }

    public static void ExportCVS(String path, List<Map<String, String>> list, Map<String, String> head, String encoding)
            throws Exception {
        File file = new File(path);
        if (!file.exists()) {
            file.createNewFile();
        }

        int index = 0;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file, true);
            for (Map<String, String> en : list) {
                if (0 == index++) {
                    for (Map.Entry<String, String> entry : head.entrySet()) {
                        if (en.containsKey(entry.getKey())) {
                            StringBuffer sb = new StringBuffer();
                            sb.append("\"");
                            sb.append(SetNullValue(entry.getValue(), ConvertEntity.Empty).toString().replace("\"",
                                    "\"\""));
                            sb.append("\"");
                            sb.append(",");
                            out.write(sb.toString().getBytes(encoding));
                        }
                    }
                    out.write(ConvertEntity.Enter.getBytes(encoding));
                }

                for (Map.Entry<String, String> entry : head.entrySet()) {
                    if (en.containsKey(entry.getKey())) {
                        StringBuffer sb = new StringBuffer();
                        sb.append("\"");
                        sb.append(SetNullValue(en.get(entry.getKey()), ConvertEntity.Empty).toString().replace("\"",
                                "\"\""));
                        sb.append("\"");
                        sb.append(",");
                        out.write(sb.toString().getBytes(encoding));
                    }
                }
                out.write(ConvertEntity.Enter.getBytes(encoding));
            }
            out.flush();
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != out) {
                out.close();
            }
        }
    }


    public static <T> BaseEntity<T> ConvertBaseEntity(BaseContent en, Class cls) throws Exception {
        BaseEntity<T> enBase = new BaseEntity<T>();
        enBase.setAppId(en.getAppId());
        enBase.setFunc(en.getFunc());
        enBase.setMethod(en.getMethod());
        enBase.setOth(en.getOth());
        enBase.setToken(en.getToken());
        enBase.setUserId(en.getUserId());
        enBase.setVersion(en.getVersion());

        if (null != cls) {
            enBase.setBody((T) ConvertEntity.copyEntity(en.getInnerBody(), cls));
        }
        return enBase;
    }

    public static <T> BaseEntity<T> ConvertBaseEntity(BaseContent en) throws Exception {
        BaseEntity<T> rtn = ConvertBaseEntity(en, null);
        return rtn;
    }

    public static Long getNextId() {
        return new SnowFlakeGenerator(0, 0).nextId();
    }

    public static <V> BaseEntity<BaseUpdateEntity<V>> ConvertToUpdateEntity(BaseContent res, Class cls) throws Exception {

        BaseEntity<BaseUpdateEntity<V>> en = new BaseEntity<>();
        en.setToken(res.getToken());
        en.setUserId(res.getUserId());
        en.setAppId(res.getAppId());
        en.setFunc(res.getFunc());
        en.setMethod(res.getMethod());
        en.setOth(res.getOth());
        en.setVersion(res.getVersion());

        en.setBody(new BaseUpdateEntity<>());
        en.getBody().setCondition((V) cls.newInstance());
        V tarEn = (V) ConvertEntity.copyEntity(res.getInnerBody(), cls);
        en.getBody().setContent(tarEn);

        return en;
    }

    public static <T> T RunUrl(String url, Map<String, String> nvps, Type type) throws IOException {
        String json = RunStringUrl(url, nvps);
        return ConvertEntity.jsonToJava(json, type);
    }

    public static <T> T RunGetUrl(String url, Map<String, String> nvps, Type type) throws Exception {
        String json = RunStringGetUrl(url, nvps);
        return ConvertEntity.jsonToJava(json, type);
    }

    public static <T> T RunObjectUrl(String url, Map<String, Object> nvps, Type type) throws IOException {
        String json = RunObjectUrl(url, nvps);
        return ConvertEntity.jsonToJava(json, type);
    }

    public static <T> T RunObjectUrlByXml(String url, Map<String, Object> nvps, Class<T> cls) throws IOException {
        List<BasicNameValuePair> list = new ArrayList();
        for (Map.Entry<String, Object> entry : nvps.entrySet()) {
            if (entry.getValue() instanceof String) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            } else {
                list.add(new BasicNameValuePair(entry.getKey(), ConvertEntity.convertToXml(entry.getValue())));
            }
        }

        String xml = RunUrl(url, list);
        return ConvertEntity.converyToJavaBean(xml, cls);
    }

    public static <T> T RunStringUrlByXml(String url, Map<String, String> nvps, Class<T> cls) throws IOException {
        List<BasicNameValuePair> list = new ArrayList();
        for (Map.Entry<String, String> entry : nvps.entrySet()) {
            list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }

        String xml = RunUrl(url, list);
        return ConvertEntity.converyToJavaBean(xml, cls);
    }

    public static <T> T RunObjectUrlStringByXml(String url, Map<String, Object> nvps, Class<T> cls) throws IOException {
        String xml = RunObjectUrlStringByXml(url, nvps);
        return ConvertEntity.converyToJavaBean(xml, cls);
    }

    public static String RunObjectUrlStringByXml(String url, Map<String, Object> nvps) throws IOException {
        List<BasicNameValuePair> list = new ArrayList();
        for (Map.Entry<String, Object> entry : nvps.entrySet()) {
            if (entry.getValue() instanceof String) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            } else {
                list.add(new BasicNameValuePair(entry.getKey(), ConvertEntity.convertToXml(entry.getValue())));
            }
        }

        return RunUrl(url, list);
    }

    public static String RunStringUrl(String url, Map<String, String> nvps) throws IOException {
        List<BasicNameValuePair> list = new ArrayList();
        if (null != nvps)
            for (Map.Entry<String, String> entry : nvps.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

        return RunUrl(url, list);
    }

    public static String RunStringGetUrl(String url, Map<String, String> nvps) throws Exception {
        List<BasicNameValuePair> list = new ArrayList();

        if (null != nvps)
            for (Map.Entry<String, String> entry : nvps.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

        return RunGetUrl(url, list);
    }

    public static String RunObjectUrl(String url, Map<String, Object> nvps) throws IOException {
        List<BasicNameValuePair> list = new ArrayList();
        for (Map.Entry<String, Object> entry : nvps.entrySet()) {
            if (entry.getValue() instanceof String) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            } else {
                list.add(new BasicNameValuePair(entry.getKey(), ConvertEntity.javaToJson(entry.getValue())));
            }
        }

        return RunUrl(url, list);
    }

    public static String RunGetUrl(String url, List<BasicNameValuePair> nvps) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).setConnectTimeout(6000).build();
        HttpGet httpLink = null;
        HttpResponse responseVal = null;
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(url);
            if (null != nvps) {
//                sb.append("?v=" + new Date().getTime());
                for (int i = 0; i < nvps.size(); i++) {
                    BasicNameValuePair vp = nvps.get(i);
                    if (i == 0) {
                        sb.append(String.format("%s=%s", vp.getName(), Encode(vp.getValue())));
                    } else {
                        sb.append(String.format("&%s=%s", vp.getName(), Encode(vp.getValue())));
                    }
                }
                for (BasicNameValuePair vp : nvps) {

                }
            }
            httpLink = new HttpGet(sb.toString());
            httpLink.setConfig(requestConfig);
            responseVal = httpClient.execute(httpLink);
            HttpEntity entity = responseVal.getEntity();

            return EntityUtils.toString(entity);
        } finally {
            if (null != responseVal) {
                ((CloseableHttpResponse) responseVal).close();
            }

            if (null != httpClient) {
                ((CloseableHttpClient) httpClient).close();
            }
        }
    }

    public static String RunUrl(String url, List<BasicNameValuePair> nvps) throws IOException {
        HttpClient httpClient = HttpClientBuilder.create().build();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).setConnectTimeout(6000).build();
        HttpPost httpLink = null;
        HttpResponse responseVal = null;
        try {
            httpLink = new HttpPost(url);
            httpLink.setConfig(requestConfig);
            httpLink.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            responseVal = httpClient.execute(httpLink);
            HttpEntity entity = responseVal.getEntity();

            return EntityUtils.toString(entity);
        } finally {
            if (null != responseVal) {
                ((CloseableHttpResponse) responseVal).close();
            }

            if (null != httpClient) {
                ((CloseableHttpClient) httpClient).close();
            }
        }
    }

    public static <T> T RunUrlXmlBody(String url, String body, Class<T> cls) throws IOException {
        String xml = RunUrlBody(url, body);
        return ConvertEntity.converyToJavaBean(xml, cls);
    }

    public static <T> T RunUrlJsonBody(String url, String body, Class<T> cls) throws IOException {
        String xml = RunUrlBody(url, body);
        return ConvertEntity.jsonToJava(xml, cls);
    }

    public static String RunUrlBody(String url, String body) throws IOException {
        HttpClient httpClient = HttpClientBuilder.create().build();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).setConnectTimeout(6000).build();
        HttpPost httpLink = null;
        HttpResponse responseVal = null;
        try {
            httpLink = new HttpPost(url);
            httpLink.setConfig(requestConfig);
            httpLink.setEntity(new StringEntity(body));
            responseVal = httpClient.execute(httpLink);
            HttpEntity entity = responseVal.getEntity();

            return EntityUtils.toString(entity);
        } finally {
            if (null != responseVal) {
                ((CloseableHttpResponse) responseVal).close();
            }

            if (null != httpClient) {
                ((CloseableHttpClient) httpClient).close();
            }
        }
    }

}
